//
//  WNUserInfoVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/15.
//

import UIKit

class WNUserInfoVC: WNBaseVC {
    
    lazy var headerView: UserInfoView = {
        let view = UserInfoView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 120))
        view.headerBtn.rx.tap.bind{ [weak self] in
            WNPhotoManager.shared.wn_openPhotoImage(0)
        }.disposed(by: rx.disposeBag)
        view.caremaBtn.rx.tap.bind{ [weak self] in
            WNPhotoManager.shared.wn_openPhotoImage(0)
        }.disposed(by: rx.disposeBag)
        return view
    }()
    
    lazy var tableView: WNTableView = {
        let tab = WNTableView.init(frame: CGRect.zero, style: .plain)
        tab.delegate = self
        tab.dataSource = self
        tab.register(UserInfoCell.self, forCellReuseIdentifier: UserInfoCell.identifier)
        tab.isScrollEnabled = false
        tab.rowHeight = 88
        tab.tableHeaderView = headerView
        return tab
    }()
    
    lazy var saveBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Save", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.rx.tap.bind { [weak self] in
            self?.changeInfoRequst()
        }.disposed(by: rx.disposeBag)
        btn.backgroundColor = WNColor.Fade().left2right(.init(width: scaleWidth(240), height: 44))
        btn.wn_cornerWithBorder(22)
        return btn
    }()
        
    var chooseImage: UIImage?
    
    var userModel: UserDetailModel? {
        didSet {
            headerView.headerBtn.wn_setupImg(userModel?.avatar, placeHolder: "placeholder_header")
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(tableView)
        view.addSubview(saveBtn)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(NaviTotalHeight)
            make.left.bottom.right.equalTo(0)
        }
        saveBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-TabBarMargin-42)
            make.width.equalTo(scaleWidth(240))
            make.height.equalTo(44)
        }
    }
    
    override func dataConfig() {
        pageName = "Profile"
        navView.titleName = "Profile"
        WNPhotoManager.shared.avatarClosure = { [weak self] avatarUrl in
            self?.userModel?.avatar = avatarUrl
            self?.tableView.reloadData()
        }
        userModel = getUser()
    }
}

extension WNUserInfoVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: UserInfoCell.identifier, for: indexPath) as! UserInfoCell
        cell.model = userModel
        cell.editType = indexPath.row
        cell.nameView.delegate = self
        cell.editClosure = {
            if indexPath.row == 0 {
                cell.nameView.becomeFirstResponder()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 1:
            showPickVC(true, .sex, 1, "\(getUser()?.sex ?? 0)") { [weak self] str in
                self?.userModel?.sex = wn_toInt(str)
                tableView.reloadRows(at: [indexPath], with: .none)
            }
        case 2:
            showPickVC(true, .birthday, 3, wn_toString(getUser()?.birthday)) { [weak self] str in
                self?.userModel?.birthday = str
                tableView.reloadRows(at: [indexPath], with: .none)
            }
        default:
            break
        }
    }
}

extension WNUserInfoVC: UITextViewDelegate {
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text.count > 0 {
            let range = NSMakeRange(textView.text.count-1, 0)
            textView.scrollRangeToVisible(range)
        }
    }
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > WNRegex.NameMaxLen {
            let selectRange = textView.markedTextRange
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            let textContent = textView.text
            let textNum = textContent?.count
            if textNum! > WNRegex.NameMaxLen {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: WNRegex.NameMaxLen)
                let str = String(textContent![..<index!])
                textView.text = str
            }
        }
        userModel?.realName = textView.text
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            return false
        }
        return true
    }
}

extension WNUserInfoVC {
    
    func changeInfoRequst() {
        if userModel?.realName == getUser()?.realName && userModel?.avatar == getUser()?.avatar && userModel?.sex == getUser()?.sex && userModel?.birthday == getUser()?.birthday {
            navigationController?.popViewController(animated: true)
            return
        }
        guard userModel?.realName?.count != 0 else {
            wn_toast("Nickname can't be empty")
            return
        }
        guard WNRegex(WNRegex.namePattern).match(input: userModel?.realName ?? "") else {
            wn_toast("Nickname must be character, numbers or _")
            return
        }
        WNHUD.wn_showLoading()
        provider_user.rx.request(.changeUserInfo(userModel?.avatar ?? "", userModel?.realName ?? "", userModel?.sex ?? 0, userModel?.birthday ?? ""))
            .asObservable().mapModel(BaseModel<Bool>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                self?.wn_toast(model.msg ?? "")
                saveUser(user: self?.userModel)
                WNThread.wn_delay(0.2) {
                    self?.navigationController?.popViewController(animated: true)
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
}

class UserInfoView: UIView {
    
    lazy var headerBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.imageView?.contentMode = .scaleAspectFill
        btn.wn_cornerWithBorder(50)
        return btn
    }()
    
    lazy var caremaBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "user_info_camera"), for: .normal)
        btn.backgroundColor = .init(white: 0, alpha: 0.35)
        btn.wn_cornerWithBorder(14)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(headerBtn)
        addSubview(caremaBtn)
        headerBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
            make.width.height.equalTo(100)
        }
        caremaBtn.snp.makeConstraints { make in
            make.right.equalTo(headerBtn.snp.right)
            make.bottom.equalTo(headerBtn.snp.bottom)
            make.width.height.equalTo(28)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
